package com.keter.common.domain.user;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.keter.common.util.PasswordEncoderUtil;
import com.keter.framework.core.exception.ValidateException;
import com.keter.framework.persist.base.BaseModel;
import com.keter.framework.persist.util.ValidateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class User extends BaseModel<User> {
    /*正常*/
    public final static String STATUS_NORMAL ="0";

    /*缺省的用户角色ID*/
    public final static String ROLE_DEFAULT_ID ="99";
    /*机构管理员角色ID*/
    public final static String ROLE_ORG_ADMIN_ID ="2";

    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(User.class);


    /* 单表操作不需要增强对象 */
    private static final User dao = new User();

    public static User findUserById(String id) {
      return dao.findById(id);
    }

    public static List<User> findAllUsers() {
        return dao.find("select * from user");
    }

    public static boolean update(User user) {
        // 逻辑校验
        new ValidateUtil(user)
            .min("name", 1)
            .max("remark",100)
        ;
        // 移除不允许更新的字段
        user
            .remove("password")
            .remove("username");
        return user.update();
    }

    public static List<User> findOrgIdsByUserId(Object id) {
        String sql =
                " SELECT o.id " +
                " from user u, user_org uo, org o " +
                " WHERE u.id =?  " +
                " AND u.id=uo.user_id and o.id = uo.org_id";
        return dao.find(sql,id);
    }

    public static List<User> findUsersWithOrgInIds(String ids) {
        //TODO:通过外连接显示未加入组织机构的用户信息
        String sql =
                " SELECT u.id, u.NAME, u.email, u.mobile, o.NAME as associator_name  " +
                " from user u, user_org uo, org  o " +
                " WHERE u.id IN("+extractCommaStrToSqlIn(ids)+")  " +
                " AND u.id=uo.user_id and o.id = uo.org_id";
        return dao.find(sql);
    }

    public static User findByUsername(String username) {
        User user = dao.findFirst(
        "select id,username,password,email,status from user where username=?",username);
        if(user==null){
            return null;
        }
        List<Record> roles = Db.find(
                " select r.id, r.name from role r, user_role ur "
                  + " where ur.user_id=? and ur.role_id=r.id"
                ,user.getNumber("id")
        );
        if(roles==null || roles.isEmpty()){
            throw new ValidateException("用户角色不能为空!");
        }
        user.put("authorities",getAuthoritiesFromRoles(roles));
        return user;
    }

    /**
     * 保存用户、角色和组织机构的对应关系
     * @return
     */
    @Override
    public boolean save() {
        return Db.tx(() -> {
            saveUser();
            Record userRole = new Record()
                    .set("user_id", this.getID())
                    .set("role_id", this.get("role_id"));
            Db.save("user_role", userRole);

            Record userOrg = new Record()
                    .set("user_id", this.getID())
                    .set("org_id", this.get("org_id"));
            Db.save("user_org", userOrg);
            return true;
        });
    }

    public static Record updatePassword(String id, String oldPass, String newPass) {
        User user = User.findUserById(id);

        // 校验密码正确性
        if(!PasswordEncoderUtil.matches(oldPass, user.get("password"))){
            throw new ValidateException("原始密码输入错误！");
        }

        // 校验新密码格式
        new ValidateUtil(user).min("password", 1);

        Record r = new Record();
        r.set("id",id);
        r.set("password",PasswordEncoderUtil.encode(newPass));
        Db.update("user", r);
        return r;
    }

    private static JSONArray getAuthoritiesFromRoles(List<Record> roles){
        JSONArray authorities = new JSONArray();
        for (Record record : roles) {
            authorities.add(record.getStr("name"));
        }
        return authorities;
    }

    /**
     * 保存用户表信息
     * @return
     */
    private boolean saveUser(){
        //单独编写新建时的特殊校验逻辑，避免更新时无法通过校验
        validator()
                .min("name", 1)
                .min("username", 1)
                .min("email", 1)
                .min("password", 1)
                .notEmpty("role_id")
                .notEmpty("org_id");
        //设定一些故有逻辑
        this.set("password", PasswordEncoderUtil.encode(this.get("password")));
        return super.save();
    }

    @Override
    public void validate() {
    }
}